package br.com.async.agilequiz.dao;

import java.util.List;

import android.database.SQLException;
import br.com.async.agilequiz.database.DatabaseHelper;
import br.com.async.agilequiz.domain.Area;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

public class AreaDao {
	
	Dao<Area, Integer> areaDao;
	
	public AreaDao(DatabaseHelper db){
		try {
			areaDao = db.getDao(Area.class);
		} catch (SQLException e) {
			// TODO: Exception Handling
			e.printStackTrace();
		} catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void create(Area area){
		try {
			areaDao.create(area);
			System.out.println("area created!");
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void update(Area area){
		try {
			areaDao.update(area);
			System.out.println("area updated!");
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void delete(Area area){
		try {
			areaDao.delete(area);
			System.out.println("area deleted!");
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Area getAreaById(Integer id){
		try{
			
			QueryBuilder<Area, Integer> qb = areaDao.queryBuilder();
			qb.where().eq("id",id);
			PreparedQuery<Area> pq = qb.prepare();
			return areaDao.queryForFirst(pq);
			
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public Area getareaByName(String name){		
		try {
			QueryBuilder<Area, Integer> qb = areaDao.queryBuilder();
			
			//qb.where().eq("name", name);
			qb.where().like("name","%"+name+"%");
			
			PreparedQuery<Area> pq = qb.prepare();
			
			return areaDao.queryForFirst(pq);
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	public List<Area> getAll(){		
		try {
			return areaDao.queryForAll();
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


}
